/**
 * 基于JQuery 的扩展
 */
;
(function ($) {
    'use strict';
    $.extend({
        /**
         * 获取天气信息
         * city 城市
         * success 调用成功回调
         * error 调用失败回调
         */
        weather: function (city, success, error) {
            city = city.replace("市", "").replace("区", "");
            $.ajax({
                type: 'GET',
                url: 'https://www.tianqiapi.com/api/',
                data: 'appid=95283593&appsecret=7HoIsjEB&version=v1&city=' + encodeURIComponent(city),
                dataType: 'JSON',
                error: function () {
                    if (error) error();
                },
                success: function (res) {
                    var weat = {
                        city: res.city, //城市名称
                        wea: res.data[0].wea, //天气情况
                        tem: res.data[0].tem, //温度
                        tems: [res.data[0].tem1, res.data[0].tem2], //温度变化区间
                        win: res.data[0].win[0], //风力
                        win_speed: res.data[0].win_speed, //风向
                        humidity: res.data[0].humidity + '%' //湿度
                    };
                    success(weat);
                }
            });
        },

        /*获取当前时间 */
        getTime: function () {
            var date = new Date();
            var weeks = new Array("日", "一", "二", "三", "四", "五", "六");
            var y = date.getFullYear();
            var m = padZero(date.getMonth() + 1);
            var d = padZero(date.getDate());
            var h = padZero(date.getHours());
            var minute = padZero(date.getMinutes());
            var s = padZero(date.getSeconds());
            return {
                y,
                m,
                d,
                h,
                M: minute,
                s,
                w: weeks[date.getDay()]
            }

            //补零操作
            function padZero(arg) {
                if (arg < 10)
                    arg = "0" + arg;
                return arg;
            }
        },

        /**
         * 全屏指定区域
         */
        fullPage: function (el, tag) {
            var el = $(el).get(0);
            if (tag) {
                if (el.requestFullscreen) {
                    el.requestFullscreen();
                } else if (el.webkitRequestFullScreen) {
                    el.webkitRequestFullScreen();
                } else if (el.mozRequestFullScreen) {
                    el.mozRequestFullScreen();
                } else if (el.msRequestFullscreen) {
                    el.msRequestFullscreen();
                }
            } else {
                if (document.exitFullscreen) {
                    document.exitFullscreen();
                } else if (document.webkitCancelFullScreen) {
                    document.webkitCancelFullScreen();
                } else if (document.mozCancelFullScreen) {
                    document.mozCancelFullScreen();
                } else if (document.msExitFullscreen) {
                    document.msExitFullscreen();
                }
            }
        },

        /**
         * 获取数据
         */
        ajaxGet: function (url, date, fn) {
            $.ajax({
                type: 'GET',
                url: url,
                data: date,
                dataType: 'JSON',
                error: function () {
                    console.log('获取数据失败');
                },
                success: function (res) {
                    if (res.code === 200) {
                        if (fn) fn(res.data);
                    } else {
                        console.log(res.msg);
                    }
                }
            });
        },
        /**
         * 获取URL请求参数
         */
        getRequest: function () {
            var url = location.search;
            var request = new Object();
            if (url.indexOf("?") != -1) {
                var str = url.substr(1);
                var strs = str.split("&");
                for (var i = 0; i < strs.length; i++) {
                    request[strs[i].split("=")[0]] = decodeURIComponent(strs[i].split("=")[1]);
                }
            }
            return request;
        },
        /**
         * 编码
         * @param {编码字符串} value 
         */
        encode: function (value) {
            return encodeURIComponent(value);
        },
          /**
         * 图片地图
         * @param  el  地图节点 
         * @param  mapSrc 地图图片路径
         * @param  mapDefaultSrc 地图图片默认路径(加载失败时使用)
         * @param  data 个点数据
         * @param  itemFn 每项回调
         * @param  loadFn 图片地图加载回调
         */
        imgMap: function (el, mapSrc, mapDefaultSrc, data, itemFn, loadFn) {
            var $el = $(el);
            var img = mapSrc;
            var $img = $("<img>");
            $img.addClass("map-img").attr("src", img);
            $el.append($img);
            $img.on('load', function () {
                let mWidth = this.width;
                let mHeigth = this.height;
                if (loadFn) loadFn($el, mWidth, mHeigth);
                if(data && data.length > 0){
                    for (let index = 0; index < data.length; index++) {
                        const p = data[index];
                        let left = (mWidth / p.width * p.left) + 'px';
                        let top = (mHeigth / p.heigth * p.top) + 'px';
                        let $span = $("<span>")
                        $span.addClass("glyphicon glyphicon-map-marker map-tag").css({
                            left: left,
                            top: top
                        });
                        $el.append($span);
                        if (itemFn) itemFn($span, p);
                    }
                }
                
            }).error(function () {
                $(this).attr('src', mapDefaultSrc);
            })
        },

        /**
         * 刷新图片地图
         * @param  el  地图节点 
         * @param  mapSrc 地图图片路径
         * @param  mapDefaultSrc 地图图片默认路径(加载失败时使用)
         * @param  data 个点数据
         * @param  itemFn 每项回调
         * @param  loadFn 图片地图加载回调
         */    
        refreshimgMap: function (el, mapSrc, mapDefaultSrc, data, itemFn, loadFn) {
            var $el = $(el);
            var $mapImg = $(".map-img");
            var img = mapSrc;
            $mapImg.attr("src", img);
            $mapImg.off("load").on('load', function () {
                let mWidth = this.width;
                let mHeigth = this.height;
                if (loadFn) loadFn($el, mWidth, mHeigth);
                if (data && data.length > 0) {
                    for (let index = 0; index < data.length; index++) {
                        const p = data[index];
                        let left = (mWidth / p.width * p.left) + 'px';
                        let top = (mHeigth / p.heigth * p.top) + 'px';
                        let $span = $("<span>")
                        $span.addClass("glyphicon glyphicon-map-marker map-tag").css({
                            left: left,
                            top: top
                        });
                        $el.append($span);
                        if (itemFn) itemFn($span, p);
                    }
                }
            }).error(function () {
                $(this).attr('src', mapDefaultSrc);
            })
        },
        /**
         * 加载json 地图
         * @cid 客户编号
         * @id 地图编号
         * @name 地图名称
         * @fn 成功回调
         */
        jsonMap: function (cid, id, name, fn) {
            $.get(`../js/geoJson/${cid}/${id}.json`, function (mapjson) {
                echarts.registerMap(name, mapjson);
                if (fn) fn(mapjson);
            });
        },
    });
    $.fn.extend({
        /**
         * 消息滚动插件
         * @param {配置项} options 
         */
        roll: function (options) {
            var defaults = {
                speed: 1, //滚动距离
                data: []
            };
            var that = this;
            var step = 0;
            var options = $.extend(defaults, options);
            var speed = options.speed;
            var datas = options.data;
            if ($(this) == null) return;
            var $container = $(this);
            var $content = $(".ticker-content", $container);
            step = that._setDate($content, datas, step);
            var init_left = $container.width();
            $content.css({ left: parseInt(init_left) + "px" });
            if (that.time) clearInterval(that.time);
            that.time = setInterval(
                function () {
                    that._move($container, $content, speed, function () {
                        step = that._setDate($content, datas, step);
                    });
                }, 20);

            $container.bind("mouseover", function () {
                clearInterval(that.time);
            });

            $container.bind("mouseout", function () {
                that.time = setInterval(function () {
                    that._move($container, $content, speed, function () {
                        step = that._setDate($content, datas, step);
                    });
                }, 20);
            });

            //释放资源
            that.destroy=function(){
                $content.removeAttr('style').empty();//重置内容
                $container.unbind('mouseover').unbind('mouseout');
                speed=1;
                datas=null;
                $content=null;
                $container=null;
                clearInterval(that.time);
                that.time=null;
            }
            return that;
        },
        _move: function ($container, $content, speed, callback) {
            var container_width = $container.width();
            var content_width = $content.width();
            var left = parseInt($content.css("left"));
            if (left + content_width > 0) {
                $content.css({ left: left - speed + "px" });
            } else {
                if (callback) callback();
                $content.css({ left: container_width + "px" });
            }
        },
        _setDate: function ($content, data, step) {
            var s = 0;
            if(data){
                if (data.length > step) {
                    s = step + 1;
                    $content.html(data[step]);
                } else {
                    var text = data.length > 0 ? data[0] : '';
                    $content.html(text);
                }
                return s;
            }
        },
    });

})(jQuery);


/**
 * 布局插件
 */
;
(function($, window) {
    function Layout(container) {
        return new Layout.prototype.init(container);
    }
    var _this;
    Layout.prototype.init = function(container) {
        _this = this;
        this.$container = $(container);
        this.cHeigth = this.$container.height();


        this.resize = function() {
            _this.resizeContainer();
            _this.resizeLayout();
        };

        /**
         * 整体容器高度
         */
        this.resizeContainer = function() {
            var wHeigth = $('body,html').height();
            this.$container.height(wHeigth - 180); //90+40
            this.cHeigth = this.$container.height();
        };

        /**
         * 重置所有布局
         */
        this.resizeLayout = function() {
            var $cols = $('.col', this.$container); //列
            var $col;
            $.each($cols, function(idx, item) {
                //设置列高度
                $col = $(item);
                $col.css({ height: '100%' });

                //计算固定高度
                var $fixeds = $('[data-fixed]', $col);
                var fheigth = 0; //固定高度
                $.each($fixeds, function(id, it) {
                    var $it = $(it);
                    var h = $it.data('fixed');
                    $it.height(h);
                    fheigth += $it.outerHeight(true);
                });

                //动态其他
                var other = _this.cHeigth - fheigth;
                var $flexs = $('[data-flex]', $col);
                $.each($flexs, function(i, t) {
                    var $t = $(t);
                    var h = $t.data('flex');
                    var oh = $t.data("heigth") || 0;
                    $t.height((other * h / 100) - oh);
                });

            });
        }

        this.resize();
    };
    Layout.prototype.init.prototype = Layout.prototype;
    window.Layout = Layout;
    $(window).on('resize', function() {
        _this.resize();
    })
})(jQuery, window);